﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FineUI;
using SysManage.BLL;
using ZHDJ.Core;
using ZHDJ.Core.Log;
using ZHDJ.Core.Util;
using ZHDJ.Data;
using ZHDJ.Data.BLL;
using ZHDJ.Data.DataCaching;
using ZHDJ.Data.Models.BaseInfo;
using ZHDJ.Data.Models.Org;
using ZHDJ.WebPage;

namespace SysManage.Module.Org
{
    public partial class PartyOrgMemberMassEdit : PageBase
    {
        #region ViewPower

        public string id
        {
            get
            {
                if (PersonalCenter == "1")
                {
                    return CurrentUser.LoginID;
                }
                return GetQueryIntValue("id");
            }
        }

        public string PersonalCenter { get { return GetQueryIntValue("PersonalCenter"); } }

        /// <summary>
        /// 本页面的浏览权限，空字符串表示本页面不受权限控制
        /// </summary>
        public override string ViewPower
        {
            get
            {
                if (PersonalCenter == "1")
                {
                    return "";
                }
                return "PartyOrgMemberAdd";
            }
        }

        /// <summary>
        /// 用户类型 1、困难党员 2、党代表 3、志愿者、4、在职党员
        /// </summary>
        public string MemberType
        {
            get
            {
                return Request.QueryString["MemberType"] ?? "0";

            }
        }
        #endregion

        #region Page_Load

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindData();
                LoadData();
            }
        }

        public void BindData()
        {
            this.ppBranch.WindinsUrl = "../../../Share/Picker/BranchSinglePicker.aspx?BranchID=" + BranchID;
            ppBranch.Text = ControlBusiness.GetBranchPickerText(BranchID);
            ppBranch.Value = BranchID;
            if (!IsSystemAdmin)
            {
                this.ppBranch.Enabled = false;
            }
            if (PersonalCenter == "1")
            {
                ddlIsPartyWorker.Enabled = false;
            }
        }

        private void LoadData()
        {

            btnClose.OnClientClick = ActiveWindow.GetHideReference();
            if (id != "")
            {

                var current = DB.PartyOrgMembers.Find(id);
                if (current.LoginID == "admin")
                {
                    ppBranch.Enabled = false;
                }

                txtUserNo.Text = current.UserNo;
                txtUserNo.Readonly = true;
                txtUserName.Text = current.UserName;
                ppBranch.Text = ControlBusiness.GetBranchPickerText(current.BranchID);
                ppBranch.Value = current.BranchID;
                ddlIsPartyWorker.SelectedValue = current.IsPartyWorker != null && (bool)current.IsPartyWorker ? "1" : "0";
                rbGender.SelectedValue = current.Gender;
                txtMobileNo.Text = current.MobileNo;
                txtIdentityCard.Text = current.IdentityCard;
                txtNation.Text = current.Nation;
                txtNativePlace.Text = current.NativePlace;
                dtBirthday.Text = Convert.ToDateTime(current.Birthday).ToString("yyyy-MM-dd");
                txtVolunteerNo.Text = current.VolunteerNo;
                txtQQ.Text = current.QQNumber;
                txtEmail.Text = current.Email;
                txtfeitionNo.Text = current.feitionNo;
                txtAddress.Text = current.Address;
                txtRewardsPunishment.Text = current.RewardsPunishment;
                txtDemocraticAppraisal.Text = current.DemocraticAppraisal;
                hdFileId.Text = current.ImageUrl;
                if (!string.IsNullOrEmpty(hdFileId.Text))
                {
                    imgPhoto.ImageUrl = UpFileBusiness.GetFileUrl(hdFileId.Text);
                    imgPhoto.ImageWidth = Unit.Pixel(300);

                    PageContext.RegisterStartupScript("ReDoLayout();");
                }
                heHardParty.Text = current.HardPartyDescription;
                txtWorkUnit.Text = current.WorkUnit;
                txtUnitJob.Text = current.UnitJob;
                txtHukouPlace.Text = current.HukouPlace;
                txtTelephone.Text = current.Telephone;
                txtFullTimeGreduateSchool.Text = current.FullTimeGreduateSchool;
                txtFullTimeMajor.Text = current.FullTimeMajor;
                txtEducationa.Text = current.Educational;
                txtPartTimeSchool.Text = current.PartTimeSchool;
                txtPartTimeMajor.Text = current.PartTimeMajor;
                txtSecondEducaional.Text = current.SecondEducaional;
                dtBeginWorkTime.Text = current.BeginWorkTime == null ? "" : Convert.ToDateTime(current.BeginWorkTime).ToString("yyyy-MM-dd");

                ddlJobType.SelectedValue = current.JobType;
                ddlOrgRelationshipType.SelectedValue = current.OrgRelationshipType;

                var isMassesLogin = GetQueryValue("ismasses");
                if (isMassesLogin == "1")
                {
                    ddlOrgRelationshipType.Visible = false;
                }
            }
            else
            {
                var date = DateTime.Now;
                dtBirthday.Text = date.ToString("yyyy-MM-dd");

            }

        }

        private void SaveData()
        {
            string tempPassword = "123456";
            var q = DB.PartyOrgMembers;
            if ((q.Where(a => a.UserNo == txtUserNo.Text && a.LoginID != id)).Any())
            {
                Alert.Show("登陆号已存在，请重新输入！", String.Empty);
                return;
            }
            if ((q.Where(a => a.MobileNo == txtMobileNo.Text && a.LoginID != id)).Any())
            {
                Alert.Show("手机号已存在，请重新输入！", String.Empty);
                return;
            }
            if ((q.Where(a => a.IdentityCard == txtIdentityCard.Text && a.LoginID != id)).Any())
            {
                Alert.Show("身份证号已存在，请重新输入！", String.Empty);
                return;
            }

            PartyOrgMember member;
            if (id != "")
            {
                //更新
                member = q.Find(id);
                if (member == null)
                {
                    Alert.Show("参数错误！", String.Empty);
                    return;
                }
                member.ModifyTimeEx = DateTime.Now;
            }
            else
            {
                member = new PartyOrgMember();
                member.LoginID = StringHelper.NewID;
                member.CreateTime = DateTime.Now;
                member.ID = member.LoginID;
                member.UserNo = txtUserNo.Text;
                member.runSate = "-1";
                member.IsAgree = true;
                member.pwdOverTime = DateTime.Now.AddYears(1);
                member.ModifyTimeEx = DateTime.Now;
                member.Password = PasswordUtil.CreateDbPassword(tempPassword);
                DB.PartyOrgMembers.Add(member);
            }
            member.UserName = txtUserName.Text;
            member.BranchID = ppBranch.Value;
            member.IsPartyWorker = ddlIsPartyWorker.SelectedValue == "1";
            member.isPartyDeputy = false;
            member.Gender = rbGender.SelectedValue;
            member.MobileNo = txtMobileNo.Text;
            member.IdentityCard = txtIdentityCard.Text;
            member.IsIncumbency = false;
            member.Post = "";
            member.Nation = txtNation.Text;
            member.NativePlace = txtNativePlace.Text;
            member.Birthday = Convert.ToDateTime(dtBirthday.Text);
            member.PoliticsLineament = "";
            member.HardPartyDescription = this.heHardParty.Text;
            member.IsFaipule = false;
            member.WorkUnit = txtWorkUnit.Text;
            member.UnitJob = txtUnitJob.Text;
            member.HukouPlace = txtHukouPlace.Text;
            member.JoinPartyOrg = "";

            member.Telephone = txtTelephone.Text;
            member.FullTimeGreduateSchool = txtFullTimeGreduateSchool.Text;
            member.FullTimeMajor = txtFullTimeMajor.Text;
            member.Educational = txtEducationa.Text;
            member.PartTimeSchool = txtPartTimeSchool.Text;
            member.PartTimeMajor = txtPartTimeMajor.Text;
            member.SecondEducaional = txtSecondEducaional.Text;
            if (!string.IsNullOrEmpty(dtBeginWorkTime.Text))
            {
                member.BeginWorkTime = Convert.ToDateTime(dtBeginWorkTime.Text);
            }
            member.isRetireParty = false;
            member.isDeputytoNPC = false;
            member.isCPPCC = false;

            member.JobType = ddlJobType.SelectedValue;
            member.OrgRelationshipType = ddlOrgRelationshipType.SelectedValue;


                member.JoinPartyDate = null;
                member.BeRegularDate = null;
            if (!string.IsNullOrEmpty(hdFileId.Text))
            {
                member.ImageUrl = hdFileId.Text;
            }
            member.VolunteerNo = txtVolunteerNo.Text;
            member.isHardParty = false;
            member.isVolunteer = false;
            member.QQNumber = txtQQ.Text;
            member.Email = txtEmail.Text;
            member.feitionNo = txtfeitionNo.Text;
            member.Address = txtAddress.Text;
            member.RewardsPunishment = txtRewardsPunishment.Text;
            member.DemocraticAppraisal = txtDemocraticAppraisal.Text;

            //member.WorkUnit = "";
            //member.UnitJob = "";
            if (DB.SaveChanges() > 0)
            {
                RoleHelper.DeleteRole(member.LoginID, SystemParameterCaching.Get(SystemParameterKey.BranchAdminRoleID));
                if (member.IsPartyWorker == true)
                {
                    RoleHelper.AddRole(member.LoginID, SystemParameterCaching.Get(SystemParameterKey.BranchAdminRoleID));
                }

                try
                {
                    OnlineStudySystem.SyncData();
                }
                catch (Exception ex)
                {
                    Log4netHelper.WriteLog(ex);
                }
            }
            PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
        }
        #endregion

        #region Events



        protected void btnSaveClose_Click(object sender, EventArgs e)
        {
            SaveData();
            //Alert.Show("添加成功！", String.Empty, ActiveWindow.GetHidePostBackReference());

        }
        #endregion

        /// <summary>
        /// 籍贯改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /*protected void ddlPoliticsLineament_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlPoliticsLineament.SelectedValue != "1" && ddlPoliticsLineament.SelectedValue != "2")
            {
                dtJoinPartyDate.Required = false;
                dtJoinPartyDate.ShowRedStar = false;
                dtBeRegularDate.Required = false;
                dtBeRegularDate.ShowRedStar = false;
                return;
            }
            dtJoinPartyDate.Required = true;
            dtJoinPartyDate.ShowRedStar = true;
            dtBeRegularDate.Required = ddlPoliticsLineament.SelectedValue == "2";
            dtBeRegularDate.ShowRedStar = ddlPoliticsLineament.SelectedValue == "2";

        }*/


        /// <summary>
        /// 上传
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void filePhoto_FileSelected(object sender, EventArgs e)
        {
            var rs = UpFileBusiness.Upload(filePhoto, CurrentUser.LoginID, "个人头像", SysEnum.UploadFileType.uploadimage);
            if (rs.IsSuccess)
            {
                hdFileId.Text = rs.FileID;
                imgPhoto.ImageUrl = "~/" + rs.FileUrl;
                imgPhoto.ImageWidth = Unit.Pixel(300);

                PageContext.RegisterStartupScript("ReDoLayout();");
            }
            else
            {
                Alert.Show("上传失败！" + rs.Message, String.Empty);
            }
        }
    }
}